//
//  YWMeterWaitReadingTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/4/25.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWMeterWaitReadingTableViewController.h"
#import "YWSelectBuildingTableViewController.h"
#import "YWDoMeterReadingTableViewController.h"

#import "UIScrollView+EmptyDataSet.h"
#import "UIColor+CustomColors.h"
#import "MJRefresh.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWNoQrcodeRights.h"
#import "MBProgressHUD.h"

#import "DOPDropDownMenu.h"
#import "YWBuilding.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"
#import "YWLoginTool.h"
#import "YWEquipment.h"
#import "YWThisMonthReadingMeterCount.h"
#import "YWMeterReadingManager.h"

#import "YWWaitMeterReadingTableViewCell.h"

@interface YWMeterWaitReadingTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,YWSelectBuildingTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
    YWApartment *currentApartment;
    YWFloor *currentFloor;
    YWLocation *currentLocation;
    YWMeterChargeTypeObject * currentMeterChargeType;
    BOOL needReload;
    NSInteger page;
}
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) NSArray *allBuildings;
@property (nonatomic, strong) NSMutableArray *menuDataArray;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *tempDataSource;
@property (nonatomic, copy) NSString * equipmentTypeOwnCode;
@end

@implementation YWMeterWaitReadingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NSString stringWithFormat:@"待抄表(%@)",self.equipmentType.equipmentTypeName];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMeterData:) name:KPostMaterReadingSuccessNotification object:nil];
    [self setupDataSource];
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    [self.menu selectDefalutIndexPath];
    
    [self initTableView];
}

- (void)setupDataSource{
    page = 1;
    needReload = YES;
    if (currentBuilding == nil) {
        currentBuilding = [self.allBuildings count] ? self.allBuildings[0] : nil;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:currentBuilding.buildingName?:@"楼盘" style:UIBarButtonItemStylePlain target:self action:@selector(selectBuildingEvent:)];
    [self rightNowSelect];
}

- (void)initTableView{
    [self.tableView registerClass:[YWWaitMeterReadingTableViewCell class] forCellReuseIdentifier:YWWaitMeterReadingTableViewCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.tableHeaderView = _menu;
    self.tableView.estimatedRowHeight = 52.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];

//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

//- (void)refreshTop
//{
//    page = 1;
//    [self.tableView.mj_footer resetNoMoreData];
//    [self requestData:YWTableViewFreshTypeDown];
//}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    needReload = NO;
    [self rightNowSelect];
}

- (void)refreshMeterData:(NSNotification*)info{
    YWEquipment * deleteEquipment = info.userInfo[@"equipment"];
    [self.tempDataSource enumerateObjectsUsingBlock:^(YWEquipment *  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([deleteEquipment.equipmentId isEqualToString:equipment.equipmentId]) {
            [self.tempDataSource removeObject:equipment];
            *stop = YES;
        }
    }];
    [self.dataSource removeAllObjects];
    NSMutableArray * allMeterArray = [self allMeterArrayWithTempArray:self.tempDataSource];
    [self.dataSource addObjectsFromArray:allMeterArray];
    [self.tableView reloadData];
}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return self.menuDataArray.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_menuDataArray[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    }else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        return floor.floorName;
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        return location.locationName;
    }else if (indexPath.column ==3){
        YWMeterChargeTypeObject * meterChargeType = _menuDataArray[indexPath.column][indexPath.row];
        NSString * typeTitle = meterChargeType.meterChargeTypeName;
       return typeTitle;
    }
    return nil;
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    BOOL needSelect = NO;
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        if (currentApartment.apartmentId!=apartment.apartmentId) {
            needSelect = YES;
            currentApartment = apartment;
            currentFloor = nil;
            currentLocation = nil;
            
            NSMutableArray *floorMut = [NSMutableArray array];
            YWFloor *floor = [[YWFloor alloc] init];
            NSString *floorShowName = [YWLoginTool floorShowName];
            floor.floorName = floorShowName.length? floorShowName:@"楼层";
            [floorMut addObject:floor];
            
            NSArray *floorArray = [[YWBuildingManager shareManager] floorWithApartmentId:currentApartment.apartmentId];
            [floorMut addObjectsFromArray:floorArray];
            
            [_menuDataArray replaceObjectAtIndex:1 withObject:floorMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
            [_menu selectIndexPath:reloadIndexPath];
            reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
        
    } else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        if (currentFloor.floorId != floor.floorId) {
            needSelect = YES;
            currentFloor = floor;
            currentLocation = nil;
            
            NSMutableArray *locationMut = [NSMutableArray array];
            YWLocation *location = [[YWLocation alloc] init];
            NSString *locationShowName = [YWLoginTool locationShowName];
            location.locationName = locationShowName.length? locationShowName:@"位置";
            [locationMut addObject:location];
            
            NSArray *locationArray = [[YWBuildingManager shareManager] locationWithFloorId:currentFloor.floorId];
            [locationMut addObjectsFromArray:locationArray];
            
            [_menuDataArray replaceObjectAtIndex:2 withObject:locationMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        if (currentLocation.locationId != location.locationId) {
            needSelect = YES;
            currentLocation = location;
        }
    }else if (indexPath.column == 3){
        needSelect = YES;
        YWMeterChargeTypeObject *meterChargeType = _menuDataArray[indexPath.column][indexPath.row];
        currentMeterChargeType = meterChargeType?:nil;
    }
    needReload = YES;
    if (needSelect) {
        page = 1;
        [self rightNowSelect];
    }
}

- (void)rightNowSelect{
    //网络请求
    YWWeakSelf(weakSelf);
    [[YWMeterReadingManager shareManager] requestUnReadMeterArrayWithPage:page equipmentTypeCode:self.equipmentTypeOwnCode buildingId:currentBuilding.buildingId apartmentId:currentApartment.apartmentId floorId:currentFloor.floorId locationId:currentLocation.locationId meterChargeTypeId:currentMeterChargeType.meterChargeTypeId complete:^(NSArray *meterArray) {
        [weakSelf.HUD hide:YES];
        [weakSelf.tableView.mj_footer endRefreshing];
        if (needReload) {
            [weakSelf.tempDataSource removeAllObjects];
        }
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.tempDataSource addObjectsFromArray:meterArray];
        NSMutableArray * allMeterArray = [self allMeterArrayWithTempArray:weakSelf.tempDataSource];
        [weakSelf.dataSource addObjectsFromArray:allMeterArray];
        [weakSelf.tableView reloadData];
    }];
}

- (NSMutableArray*)allMeterArrayWithTempArray:(NSMutableArray *)tempArray{
    //构建二维数组
    __block NSMutableArray * allMeterArray = [NSMutableArray array];
    __block NSInteger lastfloorId = 0;
    __block NSMutableArray *array = nil;
    [tempArray enumerateObjectsUsingBlock:^(YWEquipment *  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        YWEquipment *equ = [[YWEquipmentManager shareManager] equipmentWithId:equipment.equipmentId];
        //按照设备位置LocationId分组
        NSInteger floorId = equ.floorId;
        if (lastfloorId==0 || floorId !=lastfloorId) {
            lastfloorId = floorId;
            array = [NSMutableArray array];
        }
        if (equ) {
            [array addObject:equ];
        }
        if (![allMeterArray containsObject:array] && array.count) {
            [allMeterArray addObject:array];
        }
    }];
    return allMeterArray;
}

- (void)selectBuildingEvent:(id)sender{
    YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
    selectBuildingVC.delegate = self;
    selectBuildingVC.ownBuilding = currentBuilding;
    [self.navigationController pushViewController:selectBuildingVC animated:YES];
}
#pragma mark - YWSelectBuildingTableViewControllerDelegate
- (void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        [self.navigationItem.rightBarButtonItem setTitle:building.buildingName?:@"楼盘"];
        currentBuilding = building;
        currentApartment = nil;
        currentFloor = nil;
        currentLocation = nil;
        currentMeterChargeType = nil;
        self.tempDataSource = nil;
        
        //重新构建数据
        [self.dataSource removeAllObjects];
        [self setupDataSource];
        _menuDataArray = nil;
        [self.menu selectDefalutIndexPath];
        [self.menu reloadData];
        [self.tableView reloadData];
    }
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.dataSource count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YWWaitMeterReadingTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWaitMeterReadingTableViewCellIdentifier];
    YWEquipment * equipment = self.dataSource[indexPath.section][indexPath.row];
    cell.equipment =  equipment;
    return cell;
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWMeterWaitReadingTableViewControllerForHeaderInSection";
    
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2017;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self tableViewHeadTxt:section];
    UILabel* label = [headerView viewWithTag:2017];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 30);
    return headerView;
}

-(NSString *)tableViewHeadTxt:(NSInteger)section{
    NSArray *array = [self.dataSource[section] count]>0?self.dataSource[section]:nil;
    YWEquipment * equipment = array.count?array[0]:nil;
    YWApartment * apartment = [[YWBuildingManager shareManager] apartmentWithId:equipment.apartmentId];
    YWFloor * floor = [[YWBuildingManager shareManager] floorWithId:equipment.floorId];
    NSString * locationStr = [NSString stringWithFormat:@"%@%@",apartment.apartmentName,floor.floorName];
    NSString * title = locationStr.length>0?locationStr:@"未知位置";
    return title;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断是否可以无码工作
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeMeterReadingKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"无码工作已被管理员禁止" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
    YWEquipment *equipment = self.dataSource[indexPath.section][indexPath.row];
    YWDoMeterReadingTableViewController* meterReadingVC = [[YWDoMeterReadingTableViewController alloc] init];
    meterReadingVC.equipment = equipment;
    meterReadingVC.enterFromButtonOrNoQrcode = YES;
    [self.navigationController pushViewController:meterReadingVC animated:YES];
    }
//    [YWCommonTool showTextHUDWithContent:@"请选择一个可抄表设备"];
}

#pragma mark - 懒加载
- (NSMutableArray *)menuDataArray{
    if (!_menuDataArray) {
        _menuDataArray = [NSMutableArray array];
        
        NSMutableArray *apartmentMut = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:@"楼栋";
        [apartmentMut addObject:apartment];
        
        NSArray *apartmentArray = [[YWBuildingManager shareManager] apartmentWithbuildingId:currentBuilding.buildingId];
        [apartmentMut addObjectsFromArray:apartmentArray];
        
        NSMutableArray *floorMut = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:@"楼层";
        [floorMut addObject:floor];
        
        NSMutableArray *locationMut = [NSMutableArray array];
        YWLocation *location = [[YWLocation alloc] init];
        NSString *locationShowName = [YWLoginTool locationShowName];
        location.locationName = locationShowName.length? locationShowName:@"位置";
        [locationMut addObject:location];
        
        NSMutableArray *meterChargerTypeMut = [NSMutableArray array];
        YWMeterChargeTypeObject * meterCharge = [[YWMeterChargeTypeObject alloc] init];
        meterCharge.meterChargeTypeId = 0;
        meterCharge.meterChargeTypeName = @"计费类型";
        [meterChargerTypeMut addObject:meterCharge];
        if ([self.equipmentType.equipmentTypeName isEqualToString:@"水表"]) {
            NSArray * meterChargerTypeArr = @[@{@0:@"无"},@{@(YWMeterChargeTypePersonLifeWater):@"居民生活用水"},@{@(YWMeterChargeTypeUnManagerWater):@"非经营性用水"},@{@(YWMeterChargeTypeManagerWater):@"经营性用水"},@{@(YWMeterChargeTypeSpecialWater):@"特种用水"},@{@(YWMeterChargeTypeHotelWater):@"酒店用水"}];
            [meterChargerTypeArr enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString * key = [dic allKeys][0];
                YWMeterChargeTypeObject * meterChargeType = [[YWMeterChargeTypeObject alloc] init];
                meterChargeType.meterChargeTypeId = [key integerValue];
                meterChargeType.meterChargeTypeName = [dic objectForKey:key];
                [meterChargerTypeMut addObject:meterChargeType];
            }];
        }else if ([self.equipmentType.equipmentTypeName isEqualToString:@"电表"]){
            NSArray * meterChargerTypeArr = @[@{@0:@"无"},@{@(YWMeterChargeTypePersonLifeElectric):@"居民生活用电"},@{@(YWMeterChargeTypeUnPersonLightingElectric):@"非居民照明用电"},@{@(YWMeterChargeTypeBusinessElectric):@"商业用电"},@{@(YWMeterChargeTypeUnIndustryElectric):@"非工业用电"},@{@(YWMeterChargeTypeNormalIndustryElectric):@"普通工业用电"},@{@(YWMeterChargeTypeBigIndustryElectric):@"大工业用电"},@{@(YWMeterChargeTypeHotelElectric):@"酒店用电"}];
            [meterChargerTypeArr enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString * key = [dic allKeys][0];
                YWMeterChargeTypeObject * meterChargeType = [[YWMeterChargeTypeObject alloc] init];
                meterChargeType.meterChargeTypeId = [key integerValue];
                meterChargeType.meterChargeTypeName = [dic objectForKey:key];
                [meterChargerTypeMut addObject:meterChargeType];
            }];
        }else{
            NSArray * meterChargerTypeArr = @[@{@0:@"无"},@{@(YWMeterChargeTypePersonLifeGas):@"居民生活用气"},@{@(YWMeterChargeTypeHotelGas):@"酒店用气"}];
            [meterChargerTypeArr enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString * key = [dic allKeys][0];
                YWMeterChargeTypeObject * meterChargeType = [[YWMeterChargeTypeObject alloc] init];
                meterChargeType.meterChargeTypeId = [key integerValue];
                meterChargeType.meterChargeTypeName = [dic objectForKey:key];
                [meterChargerTypeMut addObject:meterChargeType];
            }];
        }
        
        [_menuDataArray addObject:apartmentMut];
        [_menuDataArray addObject:floorMut];
        [_menuDataArray addObject:locationMut];
        [_menuDataArray addObject:meterChargerTypeMut];
    }
    return _menuDataArray;
}

- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = @"查询中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}


- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] allBuilding]];
    }
    return _allBuildings;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray*)tempDataSource{
    if (!_tempDataSource) {
        _tempDataSource = [NSMutableArray array];
    }
    return _tempDataSource;
}

- (NSString*)equipmentTypeOwnCode{
    if (!_equipmentTypeOwnCode) {
        if ([self.equipmentType.equipmentTypeName isEqualToString:@"水表"]) {
            _equipmentTypeOwnCode = @"Water_Meter";
        }else if ([self.equipmentType.equipmentTypeName isEqualToString:@"电表"]){
            _equipmentTypeOwnCode = @"Electric_Meter";
        }else{
            _equipmentTypeOwnCode = @"Gas_Meter";
        }
    }
    return _equipmentTypeOwnCode;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
